from django.shortcuts import render
from django.http import HttpResponse
from picapp.models import Pictures
from datetime import datetime
import time,os
from PIL import Image
from django.core.paginator import Paginator

# Create your views here.

def upload(request):
    '''执行图片的上传'''
    myfile = request.FILES.get("mypic",None)
    print(myfile)
    if not myfile:
        return None
    filename = str(time.time())+"."+myfile.name.split('.').pop()
    destination = open("./static/pics/"+filename,"wb+")
    for chunk in myfile.chunks():      # 分块写入文件  
        destination.write(chunk)  
    destination.close()

    # 执行图片缩放
    im = Image.open("./static/pics/"+filename)
    # 缩放到75*75(缩放后的宽高比例不变):
    im.thumbnail((75, 75))
    # 把缩放后的图像用jpeg格式保存: 
    im.save("./static/pics/s_"+filename,None)

    return filename

def removePics(filename):
	'''执行删除图片文件'''
	os.remove("./static/pics/"+filename)
	os.remove("./static/pics/s_"+filename)

def index(request):
	'''加载首页'''
	return render(request,"picapp/index.html")

def indexPics(request, pIndex):
    '''分页浏览相册信息'''
    picslist = Pictures.objects.all()	#获取图片列表
    p = Paginator(picslist,5)			#每页5行

    if pIndex == "":
        pIndex = "1"
    pagelist = p.page(pIndex)			#获取当前显示页图片列表
    prlist = p.page_range				#获取页码清单

    #将相册信息封装到字典中
    context = {"picslist":pagelist,"prlist":prlist,"pIndex":int(pIndex)}
    #加载模板，并传递信息
    return render(request,"picapp/picman/index.html",context)

def addPics(request):
	'''加载添加相册信息表单'''
	return render(request,"picapp/picman/addpic.html")

def insertPics(request):
	'''执行添加相册信息'''
	try:
		if request.POST['title']=="":
			context = {"info":"没有输入图片标题！"}
		else:
			# 执行图片的上传
			filename = upload(request)

			if not filename:
				context = {"info":"没有上传文件信息！"}
			else:
				#获取并封装相册图片信息
				pic = Pictures()
				pic.title = request.POST['title']
				pic.filename = filename
				pic.createdate = datetime.now()
				pic.save()
				context = {"info":"添加成功！"}
	except:
		context = {"info":"添加失败！"}

	return render(request, "picapp/picman/info.html", context)

def editPics(request,pid):
	'''加载修改相册信息表单'''
	try:
		pic = Pictures.objects.get(id=pid)
		context = {"pic":pic}
		return render(request,"picapp/picman/editpic.html",context)

	except Exception as err:
		print(err)
		context = {"info":"没有找到要修改的相册信息！"}
		return render(request,"picapp/picman/info.html",context)

def delPics(request,pid):
	'''删除相册信息'''
	try:
		pic = Pictures.objects.get(id=pid)
		removePics(pic.filename)
		pic.delete()
		context = {"info":"删除成功！"}
	except:
		context = {"info":"删除失败！"}
	return render(request,"picapp/picman/info.html",context)

def updatePics(request):
	'''执行相册信息修改'''
	try:
		if request.POST['title']=="":
			context = {"info":"没有输入图片标题！"}
		else:
			pic = Pictures.objects.get(id=request.POST['id'])
			pic.title = request.POST['title']
			pic.createdate = datetime.now()

			# 执行新的图片文件上传
			filename = upload(request)
			
			if not filename:				#没有新图片上传文件信息
				pass
			else:							#新图片文件上传成功
				removePics(pic.filename)
				pic.filename = filename
			
			pic.save()
			context = {"info":"修改成功！"}
	except:
		context = {"info":"修改失败！"}
	return render(request, "picapp/picman/info.html", context)

